package org.hefan.hrm.config;

import org.hefan.hrm.handler.DefaultAccessDeniedHandler;
import org.hefan.hrm.handler.MyAuthenticationFailureHandler;
import org.hefan.hrm.handler.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DefaultAccessDeniedHandler defaultAccessDeniedHandler;

    @Autowired
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;

    @Autowired
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;

    @Autowired
    private PersistentTokenRepository repository;

    @Autowired
    private UserDetailsService userDetailsService;

     //提供用户信息，这里没有从数据库查询用户信息，在内存中模拟
//    @Bean
//    public UserDetailsService userDetailsService(){
//        InMemoryUserDetailsManager inMemoryUserDetailsManager =
//        new InMemoryUserDetailsManager();
//        inMemoryUserDetailsManager.createUser(User.withUsername("zs").password("123").authorities("admin").build());
//        return inMemoryUserDetailsManager;
//    }
  

    //密码编码器：不加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        //return NoOpPasswordEncoder.getInstance();
        // 现在加密
        return new BCryptPasswordEncoder();
    }
    
    //授权规则配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()                                //授权配置
                .antMatchers("/login").permitAll()  //登录路径放行
                .antMatchers("/login.html").permitAll() // 放行自定义的登录页面
                .anyRequest().authenticated()                   //其他路径都要认证之后才能访问
                .and().formLogin()                              //允许表单登录
                //.successForwardUrl("/loginSuccess")             // 设置登陆成功页
                .successHandler(myAuthenticationSuccessHandler) // 自定义登陆成功页面
                .failureHandler(myAuthenticationFailureHandler) // 自定义登陆失败页面

                .loginPage("/login.html") // 没有登录跳转的页面
                .loginProcessingUrl("/login") // 登录处理地址
                .and().logout().permitAll()                    //登出路径放行 /logout
                .and().csrf().disable();                        //关闭跨域伪造检查

        // 没有访问权限的处理
        http.exceptionHandling().accessDeniedHandler(defaultAccessDeniedHandler);

        //记住我
        http.rememberMe()
                .tokenRepository(repository)
                .tokenValiditySeconds(3600)
                .userDetailsService(userDetailsService);
    }

    /**
        记住我功能实现配置如下：
     */
    @Bean
    public PersistentTokenRepository repository(){
        JdbcTokenRepositoryImpl repository = new JdbcTokenRepositoryImpl();
        repository.setDataSource(dataSource()); //要访问数据库必须设置数据源
//        repository.setCreateTableOnStartup(true); //自己见persistent_logins
        return  repository;
    }

    /**
     * mybatisPlus坑的地方
     * 不能注入dataSource
     * 需要自己手动连接数据库
     * @return
     */
    @Bean
    @Primary//主数据源
    @ConfigurationProperties("spring.datasource1")
    public DataSource dataSource(){
        return DataSourceBuilder.create().build();
    }
}